package com.example.crud.infrastructure.persistence.impl;

import com.example.crud.data.dto.StudentListItemQueryDTO;
import com.example.crud.data.entity.Student;
import com.example.crud.data.repository.StudentRepository;
import com.example.crud.infrastructure.persistence.converter.StudentConverter;
import com.example.crud.infrastructure.persistence.dataobj.StudentDO;
import com.example.crud.infrastructure.persistence.mapper.StudentDOMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
@RequiredArgsConstructor
public class StudentRepositoryImpl implements StudentRepository {

    private final StudentDOMapper dao;
    private final StudentConverter converter = StudentConverter.INSTANCE;

    @Override
    public void save(Student student) {
        StudentDO studentDO = converter.toStudentDO(student);
        dao.save(studentDO);
    }

    @Override
    public Optional<Student> findById(String id) {
        return Optional.ofNullable(dao.findById(id)).map(converter::toStudent);
    }

    @Override
    public void update(Student student) {
        StudentDO studentDO = converter.toStudentDO(student);
        dao.updateById(studentDO);
    }

    @Override
    public Optional<Student> removeById(String id) {
        Optional<StudentDO> optional = Optional.ofNullable(dao.findById(id));

        optional.ifPresent((e) -> dao.deleteById(id));
        return optional.map(converter::toStudent);
    }

    @Override
    public boolean exists(String id) {
        return dao.countById(id) > 0;
    }

    @Override
    public List<StudentListItemQueryDTO> findAll() {
        return dao.findAll();
    }
}
